//function to style checkbox and radio buttons


// Format Currency
Number.prototype.formatMoney = function (c, d, t) {
    var n = this,
        c = isNaN(c = Math.abs(c)) ? 2 : c,
        d = d == undefined ? "." : d,
        t = t == undefined ? "," : t,
        s = n < 0 ? "-" : "",
        i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
        j = (j = i.length) > 3 ? j % 3 : 0;
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};

//function  increase/ decrease product qunatity buttons +/-
function change_qty(container) {
    var container = container;
    var input = jQuery(container).find('input:text');
    default_val = jQuery(input).val();
    var j = default_val;
    remove = jQuery(container).find('span.minus_qty');
    add = jQuery(container).find('span.plus_qty');

    add.on('click', function () {
        j = jQuery(input).val();
        j++;
        jQuery(input).val(j);
    });

    remove.on('click', function () {
        j = jQuery(input).val();
        if (j > 1) {
            j--;
            jQuery(input).val(j);
        } else {
            j = 1;
        }
    });

    input.blur(function () {
        if (jQuery(this).val() <= 0) {
            j = 1;
            jQuery(this).val(1);
        } else {
            j = jQuery(this).val();
        }
    });
}


// functon to scrolle to an div  widh the ID ?
function windowScrollTo(id) {
    (function ($) {
        var hashContainer = $('#' + id),
            hashContainerPos = hashContainer.position().top;
        $('html, body').animate({scrollTop: hashContainerPos}, 'slow');
    })(jQuery);
}


// product page image magnify zoom
function activate_jqzoom(type, effect) {
    (function ($) {
        if (effect == 'fade') {
            show = 'fadein';
            hide = 'fadeout';
        } else {
            show = 'show';
            hide = 'hide';
        }
        $('.jqzoom').jqzoom({
            zoomType: type,
            lens: true,
            preloadImages: true,
            alwaysOn: false,
            zoomWidth: 300,
            zoomHeight: 680,
            xOffset: 10,
            yOffset: 10,
            showEffect: show,
            hideEffect: hide,
            position: 'left'
        });
    })(jQuery);
}


jQuery(document).ready(function ($) {

    // show search form	
    if ($('.search-popup-trigger')[0]) {
        $('#top-search-wrapper').css({'right': -50});

        $('.search-popup-trigger').click(function (event) {
            event.preventDefault();

            $('#top-search-wrapper').toggleClass('show-search');
            if ($('#top-search-wrapper').hasClass('show-search')) {
                $('#top-search-wrapper').css({'display': 'block'}).animate({'opacity': 1, 'right': -20}, 450, 'easeOutExpo');
            }
            else {
                $('#top-search-wrapper').animate({'opacity': 0, 'right': -50}, 450, 'easeOutExpo', function () {
                    $(this).css({'display': 'none'})
                });

            }
        });
    }


    //mobile menu youtube style slide

    if ($('.mobile-icon-menu')[0]) {
        $('.mobile-icon-menu').click(function (event) {
            event.preventDefault();
            $(this).toggleClass('show-mobile');
            if ($(this).hasClass('show-mobile')) {
                $(this).animate({'left': '100%'}, 250, 'linear',function () {
                    $('ul.primary-nav li').not('.search-wrapper').slideDown();
                }).html('&#xe0010;');
                $('.menu-label').animate({'left': -50}, 100, 'linear');
            }
            else {
                $(this).animate({'left': 0}, 250, 'linear').html('&#xe008;');
                $('.menu-label').animate({'left': 0}, 100, 'linear');
                $('ul.primary-nav li').not('.search-wrapper').slideUp();

            }
        });
    }


    change_qty($('.price-data-box'));


    if ($('td.quantity')[0]) {
        $('td.quantity').each(function () {
            change_qty($(this));
        });
    }

    // category-grid template categories slider
    if ($('.flexslider-categories')[0]) {
        $('.flexslider-categories').flexslider({
            animation: "slide",
            itemWidth: 90,
            itemMargin: 0,
            minItems: 1,
            maxItems: 4,
            selector: ".slides > li",
            prevText: "&#xe00e;",
            nextText: "&#xe011;",
            controlNav: false,
        });
    }

    // Homepage  Template (index.html ) product quick view slider
    if ($('.offers-box .flexslider')[0]) {
        $('.offers-box .flexslider').flexslider({
            animation: "slide",
            itemWidth: 234,
            itemMargin: -2,
            minItems: 1,
            slideshow: true,
            maxItems: 4,
            selector: ".slides > li",
            prevText: "&#xe00e;",
            nextText: "&#xe011;",
            controlNav: false
        });
    }

    // Homepage tmp (index2.html ) quick view plguin
    if ($("a[rel^='prettyPopin']")[0]) {
        $("a[rel^='prettyPopin']").prettyPopin({width: 460});
    }

    // Homepage tmp (index2.html ) featured slider
    if ($('.swiper-main')[0]) {
        var swiper = new Swiper('.swiper-main', {
            slideClass: 'swiper-slide',
            wrapperClass: 'swiper-container',
            loop: true,
            ratio: 1,
            speed: 300,
            freeMode: false,
            freeModeFluid: false,
            slidesPerSlide: 1,
            simulateTouch: true,
            followFinger: true,
            autoPlay: 5000,
            onlyExternal: false,
            createPagination: true,
            resistance: true,
            scrollContainer: false,
            preventLinks: true,
            initialSlide: 0,
            onSlideClick: function () {
                captions = $(swiper.container).find('.caption');
                index = swiper.activeSlide;
                slide = swiper.clickedSlide;
                currCaption = captions[index + 1];
                caption = captions[index + 2];
                PrevCaption = captions[index];
                $(caption).css({
                    left: '100%',
                    opacity: 0
                }).stop(true).animate({
                        opacity: 1,
                        left: '50'
                    }, 800, 'easeOutExpo', function () {
                        currCaption = $(captions[index + 1]);
                        currCaption.css({
                            opacity: 1
                        });
                    });

                $(PrevCaption).css({
                    left: '-100%',
                    opacity: 0
                }).stop(true).animate({
                        opacity: 1,
                        left: '50'
                    }, 800, 'easeOutExpo', function () {
                        currCaption = $(captions[index + 1]);
                    });
            }
        });
        $('.arrow-left').click(function (e) {
            swiper.swipePrev();

        });
        $('.arrow-right').click(function (e) {
            swiper.swipeNext();
        });
    }

    //increase/ decrease product qunatity buttons +/- in cart.html table
    if ($('.subDropdown')[0]) {
        $('.subDropdown').click(function () {
            $(this).toggleClass('plus');
            $(this).toggleClass('minus');
            $(this).parent().find('ul').slideToggle();
        });
    }

    //product page details/ review tabs

    if ($("#tabs")[0]) {
        $("#tabs").tabs({
            activate: function (event, ui) {
                $(ui.oldTab).find('a').removeClass('active-tab');
                $(ui.newTab).find('a').addClass('active-tab');
            }
        });
    }

    //init images/views lightbox view
    if ($('.prettyphoto')[0]) {
        $('.prettyphoto').prettyPhoto();
    }

    //product page top "write review button scroll and show review form	
    $('.write_review').click(function () {
        windowScrollTo('tab-review');
    });

    //scroll to the top
    $('.gotoTop').click(function () {
        windowScrollTo('wrapper');
    });

    function scrolltop() {
        arrow = $('.gotoTop');
        window_top_pos = $(document).scrollTop();
        height_windows = $(window).height();
        if (window_top_pos > (height_windows + (height_windows / 4))) {
            arrow.stop().animate({opacity: 1});
        } else {
            arrow.stop().animate({opacity: 0});
        }
        $(document).scroll(function () {
            window_top_pos = $(document).scrollTop();
            if (window_top_pos > (height_windows + (height_windows / 4))) {
                arrow.stop().animate({opacity: 1});
            } else {
                arrow.stop().animate({opacity: 0});
            }
        });
    }

    scrolltop();


    //init  sharre plugin for blog single post page more info  http://sharrre.com
    $('#share').sharrre({
        share: {
            googlePlus: true,
            facebook: true,
            twitter: true,
            pinterest: true
        },
        buttons: {
            googlePlus: {size: 'tall', annotation: 'bubble'},
            facebook: {layout: 'box_count'},
            twitter: {count: 'vertical', via: $('#share').data('twitter-id')},
            pinterest: {description: $('#share').data('text'), layout: 'vertical'},
        },
        hover: function (api, options) {
            $(api.element).find('.buttons').show();
        },
        hide: function (api, options) {
            $(api.element).find('.buttons').hide();
        },
        enableTracking: true
    });


    var selectMenu = {
        init: function (config) {
            this.config = config;
            this.changeEvent();
        },
        changeEvent: function () {
            var self = this;
            self.config.menu.on('change', self.goToPage);
        },
        goToPage: function () {
            select_url = this.value;
            window.location.href = select_url;
        }
    }

    // header curency and language click toggle use it to assing ajax or php dynamic function to change the language or currency according to your CMS
    $('.top-select-menu').toggle(function () {
        $(this).find('a').not('.active_option').css({
            display: 'block',
            opacity: 1
        });

    }, function () {
        $(this).find('a').not('.active_option').css({
            display: 'none',
            opacity: 0
        });
    });

    // top arrow button hide/show top header
    if ($('.slide-toggle')[0]) {
        $('.slide-toggle').click(function () {
            $('#top-wrapper').slideToggle();
        });
    }

    //init mobile select menu
    selectMenu.init({
        menu: jQuery('#mobile-nav-menu')
    });


    // show cart details  in Header with click used for mobile hover no effect
    $('.click-trigger').click(function () {
        var hiddenBox = $(this).parent().find('.hidden_box');
        $(hiddenBox).toggleClass('display-click');
    });


    // featured homepage slider - function below to make it respoisnve slider 
    var $window = $(window);

    function getGridSize() {
        var container = $('.container_12').width();
        if (container >= 940) {
            return 222;
        }
        else if (container == 714) {
            return 226;
        }
        else if (container == 420) {
            return 200;
        } else if (container == 300) {
            return 300;
        }
    }

    var flexsliderFeatured = jQuery('#main-container .featured-module').flexslider({
        animation: "product-box",
        itemWidth: getGridSize(),
        itemMargin: 17.6,
        minItems: 1,
        maxItems: 4,
        selector: ".slides > div.product-box",
        prevText: "&#xe00e;",
        nextText: "&#xe011;",
        controlNav: false,
        start: function () {
            flexsliderFeatured = this;
        }
    });

    $window.resize(function () {
        var gridSize = getGridSize();
        if ($('#main_container .featured_box').length) {
            flexsliderFeatured.itemWidth = gridSize;
        }
    });
    // responsive video plugin
    if ($("#wrapper")[0]) {
        $("#wrapper").fitVids();
    }
    //product page image zoom plugin


    if ($('.vertical-slider')[0]) {
        $('.vertical-slider .flexslider').flexslider({
            animation: "slide",
            animationLoop: false,
            direction: "vertical",
            prevText: "&#xe010;",
            nextText: "&#xe00f;",
            selector: ".slides > li",
            minItems: 2,
            maxItems: 3,
            itemMargin: 50,
            controlNav: false

        });
    }

    if ($('.horizontal-slider')[0]) {
        $('.horizontal-slider .flexslider').flexslider({
            animation: "slide",
            animationLoop: false,
            prevText: "&#xe00e;",
            nextText: "&#xe011;",
            selector: ".slides > li",
            minItems: 1,
            maxItems: 3,
            controlNav: false,
            itemWidth: 95,
            itemMargin: 0
        });
    }

    if ($('.jqzoom')[0]) {
        activate_jqzoom('innerzoom', 'fade');
    }


    if ($('.responsive-slider')[0]) {
        $('.responsive-slider').flexslider({
            animation: "slide",
            prevText: "&#xe00e;",
            nextText: "&#xe011;",
            controlNav: false,
            start: function () {
                $('.flexImages').show();
            }
        });
    }

//   // Background slideshow
//  if($('#bg-slideshow')[0]){
//  	$('#bg-slideshow').kenburns({
//			images:[
//					"images/bg-slideshow/1.jpg",
//		  		"images/bg-slideshow/2.jpg",
//		  		"images/bg-slideshow/3.jpg"
//					],
//			frames_per_second: 30,
//			display_time: 7000,
//			fade_time: 1000,
//			zoom: 1.2,
//			background_color:'#000000'
//		});
//  }


    // AJAX SAVE THEME STYLE
    $('#save-style').click(function () {
        var r = confirm("Bạn có muốn lưu giao diện này hay không?")
        if (r == true) {
            jQuery.ajax({
                type: "post",
                url: azio_ajax.ajaxurl,
                dataType: 'json',
                data: ({
                    action: "azio_ajax_savestyle",
                    color: $('#get-color-style').val(),
                    body: $('#get-pattern-body').val(),
                    top_wrapper: $('#get-pattern-top-wrapper').val(),
                    header: $('#get-pattern-header').val(),
                    page_top_leader: $('#get-pattern-page-top-leader').val(),
                    main_container: $('#get-pattern-main-container').val(),
                    footer: $('#get-pattern-footer').val()
                }),
                success: function (data) {
                    alert(data.message)
                },
                error: function (data) {
                    alert('Có lỗi xảy ra vui lòng thử lại.');
                }
            });
        }
    });

    // AJAX RESTORE DEFAULT THEME STYLE
    $('#restore-default-style').click(function () {
        var r = confirm("Nếu phục hồi về mặc định, các tùy chỉnh về giao diện như hình nền, màu sắc của bạn sẽ bị thay đổi, bạn có muốn phục hồi hay không?")
        if (r == true) {
            jQuery.ajax({
                type: "post",
                url: azio_ajax.ajaxurl,
                dataType: 'json',
                data: ({
                    action: "azio_ajax_restoredefaultstyle"
                }),
                success: function (data) {
                    alert(data.message)
                },
                error: function (data) {
                    alert('Có lỗi xảy ra vui lòng thử lại.');
                }
            });
        }
    });


}); // End of Jquery ready